/* * 港到港下单 */
<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="title-icon">港到港下单</span>
      </div>
      <el-row>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="padding-40">
          <el-form
            ref="waybillInfo"
            :model="waybillInfo"
            size="mini"
            :rules="rules"
            label-position="left"
            label-width="110px"
            class="text-sm"
          >
            <el-form-item prop="shippingWay">
              <div slot="label">物流方式：</div>
              <el-radio-group v-model="waybillInfo.shippingWay">
                <el-radio label="AIR">空运 港到港 </el-radio>
                <el-radio label="FCL">海运整柜 </el-radio>
                <el-radio label="LCL">海运散货 </el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- <div class="text-gray margin-bottom-sm ">
              提交后，该票物流方法不能更改
            </div> -->

            <el-form-item prop="countryId">
              <div slot="label">目的国家：</div>
              <template>
                <el-select
                  v-model="waybillInfo.countryId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :loading="loading"
                >
                  <el-option
                    v-for="(item, value) of countryIds"
                    :key="value"
                    :label="item.label"
                    :value="parseInt(item.value)"
                  />
                </el-select>
              </template>
            </el-form-item>
            <div v-show="waybillInfo.shippingWay === 'AIR'">
              <el-form-item prop="shipmentPort">
                <div slot="label">起运港：</div>
                <template>
                  <el-select
                    v-model="waybillInfo.shipmentPort"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词"
                    :loading="loading"
                  >
                    <el-option
                      v-for="(item, value) in airlineMap"
                      :key="value"
                      :label="item"
                      :value="parseInt(value)"
                    />
                  </el-select>
                </template>
              </el-form-item>
              <el-form-item prop="destinationPort">
                <div slot="label">目的港：</div>
                <template>
                  <el-select
                    v-model="waybillInfo.destinationPort"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词"
                    :loading="loading"
                  >
                    <el-option
                      v-for="(item, value) in airlineMap"
                      :key="value"
                      :label="item"
                      :value="parseInt(value)"
                    />
                  </el-select>
                </template>
              </el-form-item>
            </div>

            <div
              v-show="
                waybillInfo.shippingWay === 'FCL' ||
                waybillInfo.shippingWay === 'LCL'
              "
            >
              <el-form-item prop="shipmentPort">
                <div slot="label">起运港：</div>
                <template>
                  <el-select
                    v-model="waybillInfo.shipmentPort"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词"
                    :loading="loading"
                  >
                    <el-option
                      v-for="(item, value) in configPortMap"
                      :key="value"
                      :label="item"
                      :value="parseInt(value)"
                    />
                  </el-select>
                </template>
              </el-form-item>
              <el-form-item prop="destinationPort">
                <div slot="label">目的港：</div>
                <template>
                  <el-select
                    v-model="waybillInfo.destinationPort"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词"
                    :loading="loading"
                  >
                    <el-option
                      v-for="(item, value) in configPortMap"
                      :key="value"
                      :label="item"
                      :value="parseInt(value)"
                    />
                  </el-select>
                </template>
              </el-form-item>
            </div>

            <el-form-item prop="customerActualWeight">
              <div slot="label">实重：</div>
              <el-input
                v-model="waybillInfo.customerActualWeight"
                placeholder="请输入实重"
                autocomplete="off"
                oninput="value=((value.replace(/[^0-9.]/g,'')).replace(/([0-9]+\.[0-9]{3})[0-9]*/,'$1'))"
              />
            </el-form-item>

            <el-form-item prop="customerTotalPackages">
              <div slot="label">件数：</div>
              <el-input
                v-model.number="waybillInfo.customerTotalPackages"
                placeholder="请输入件数"
                autocomplete="off"
              />
            </el-form-item>

            <el-form-item
              v-show="waybillInfo.shippingWay === 'AIR'"
              label="体积："
              prop="customerVolume"
              :rules="[{ required: false }]"
            >
              <el-input
                v-model="waybillInfo.customerVolume"
                oninput="value=((value.replace(/[^0-9.]/g,'')).replace(/([0-9]+\.[0-9]{3})[0-9]*/,'$1'))"
                placeholder="请输入体积"
              />
            </el-form-item>

            <el-form-item
              v-show="
                waybillInfo.shippingWay === 'FCL' ||
                waybillInfo.shippingWay === 'LCL'
              "
              prop="customerVolume"
            >
              <div slot="label">体积：</div>
              <el-input
                v-model="waybillInfo.customerVolume"
                placeholder="请输入体积"
              />
            </el-form-item>

            <el-form-item prop="isCustomerDeclaration">
              <div slot="label">是否报关：</div>
              <el-tooltip class="item" effect="light" placement="right">
                <div slot="content">
                  是指您指定用某一家具有进出口权的公司做出口申报，能自行提供整套报关单证，且后续要做出口退税的情况。请选择是。如非此情况，请选择否。
                  <br />如您此票货物中有部分货物需用一般贸易报关，其他部分不用一般贸易报关，请选择“部分报关”选项。
                </div>
                <i class="el-icon-question icon-question text-yellow" />
              </el-tooltip>

              <el-radio
                v-model="waybillInfo.isCustomerDeclaration"
                :label="parseInt(0)"
                class="margin-left"
                >否</el-radio
              >
              <el-radio
                v-model="waybillInfo.isCustomerDeclaration"
                :label="parseInt(1)"
                >是</el-radio
              >
            </el-form-item>

            <!-- <el-row :gutter="20" v-if="waybillInfo.shippingWay === 'FCL'">
                <el-col :span="12">
                  <el-form-item prop="cabinetNumber" >
                  <div slot="label">柜量：</div>
                    <el-input
                    v-model.number="waybillInfo.cabinetNumber"
                    min="0"
                    clearable
                    placeholder="请输入柜量"
                  />
                  </el-form-item>
                </el-col>
              <el-col :span="12">
              <el-form-item prop="cabinetType" >
                <div slot="label" >柜型：</div>
                <el-select
                  v-model="waybillInfo.cabinetType"
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in publicData.cabinetTypeMap"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
         </el-row>  -->

            <template v-if="waybillInfo.shippingWay === 'FCL'">
              <el-row v-for="(val, index) in boxMap" :key="index">
                <el-col :span="10">
                  <el-form-item prop="cabinetNumber">
                    <div slot="label">柜量：</div>
                    <el-input
                      v-model.number="val.cabinetNumber"
                      type="number"
                      min="0"
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item prop="cabinetType">
                    <div slot="label" class="text-right">柜型：</div>
                    <el-select
                      v-model="val.cabinetType"
                      filterable
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in publicData.cabinetTypeMap"
                        :key="item"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="4" class="margin-top-xs">
                  <el-link
                    icon="el-icon-plus"
                    :underline="false"
                    class="margin-lr-xl"
                    @click="onAdd(val)"
                  />
                  <el-link
                    icon="el-icon-minus"
                    :underline="false"
                    @click.prevent="removeDomain(val)"
                  />
                </el-col>
              </el-row>
            </template>

            <el-form-item
              v-if="waybillInfo.isCustomerDeclaration"
              label="报关资料上传："
            >
              <el-upload
                ref="upload"
                class="upload-demo"
                action="#"
                :show-file-list="false"
                :auto-upload="true"
                :http-request="uploadFn"
              >
                <el-button slot="trigger" type="primary"> 选取文件 </el-button>
              </el-upload>
              <div
                v-if="
                  waybillInfo.extraAttributes &&
                  waybillInfo.extraAttributes.length > 0
                "
              >
                <template v-for="(item, index) in waybillInfo.extraAttributes">
                  <template v-if="item.lastIndexOf('/') > -1">
                    <el-row :key="index">
                      <el-col :span="20">
                        <i class="el-icon-document" />
                        <span>{{ item.slice(item.lastIndexOf('/') + 1) }}</span>
                      </el-col>
                      <el-col :span="4" class="text-right">
                        <i
                          class="el-icon-close pointer"
                          @click="removeFile(index)"
                        />
                      </el-col>
                    </el-row>
                  </template>
                  <template v-else>
                    {{ item }}
                  </template>
                </template>
              </div>
            </el-form-item>
            <el-form-item prop="isCustomerDeclaration" v-if="buyFclLclFalg">
              <div slot="label">装柜方式：</div>
              <el-tooltip class="item" effect="light" placement="right">
                <div slot="content">
                  九方装柜：九方到客户装柜地址提货，并送货到起运港
                  <br />客户装柜：客户自行在装柜时间内，送货到起运港
                </div>
                <i class="el-icon-question icon-question text-yellow" />
              </el-tooltip>
              <el-radio
                v-model="waybillInfo.selfDelivered"
                :label="parseInt(1)"
                class="margin-left"
                >九方装柜</el-radio
              >
              <el-radio
                v-model="waybillInfo.selfDelivered"
                :label="parseInt(0)"
                >{{ showNb ? '客户送货' : '客户装柜' }}</el-radio
              >
            </el-form-item>
            <el-form-item prop="isBuyInsurance">
              <div slot="label">是否购买保险：</div>
              <el-tooltip class="item" effect="light" placement="right">
                <div slot="content">
                  a 购买为是:<br /><br />1、甲方按照产品采购货值的
                  0.3%向乙方支付保费；
                  <br />2、按照系统下单时提供的产品采购货值赔偿；
                  <br />3、无免赔，即按照产品采购货值的 100%赔偿，
                  理赔时需提供采购发票，哪个低按哪个来核算赔偿金额
                  <br />4、赔偿上限：海运整柜RMB200 万/柜 <br /><br />
                  b 购买为否<br />> 1、不填默认不买保险
                  2、如填写货值，则九方买保险，按下单货值购买保险，只赔偿货值90%，理赔时需提供采购发票，哪个低按哪个来核算赔偿金额，赔偿上限为RMB50
                  万/柜
                </div>
                <i class="el-icon-question icon-question text-yellow" />
              </el-tooltip>

              <el-radio
                v-model="waybillInfo.isBuyInsurance"
                :label="parseInt(0)"
                class="margin-left"
                >否</el-radio
              >
              <el-radio
                v-model="waybillInfo.isBuyInsurance"
                :label="parseInt(1)"
                >是</el-radio
              >
            </el-form-item>

            <div>
              <div
                v-if="buyInsuranceFlag"
                class="text-gray margin-bottom-sm"
                style="color: red"
              >
                1、不填默认不买保险<br />
                2、如填写货值，则九方买保险，按下单货值购买保险，只赔偿货值90%，理赔时需提供采购发票，哪个低按哪个来核算赔偿金额，赔偿上限为RMB50
              </div>
              <div v-else class="text-gray margin-bottom-sm" style="color: red">
                1、甲方按照产品采购货值的 0.3%向乙方支付保费；<br />
                2、按照系统下单时提供的产品采购货值赔偿；<br />
                3、无免赔，即按照产品采购货值的
                100%赔偿，理赔时需提供采购发票，哪个低按哪个来核算赔偿金额<br />
                4、赔偿上限：海运整柜RMB200 万/柜
              </div>
            </div>

            <el-form-item prop="totalPurchasingPrice">
              <div slot="label">采购总价(RMB)：</div>
              <el-input
                v-model.number="waybillInfo.totalPurchasingPrice"
                placeholder="购买保险必填"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item label="品名：">
              <el-input
                v-model="waybillInfo.nameDescription"
                type="textarea"
                placeholder="购买保险必填"
                :rows="4"
                clearable
              />
            </el-form-item>
            <div
              v-show="waybillInfo.selfDelivered"
              class="flex justify-end margin-bottom-sm"
            >
              <span
                style="color: #409eff"
                class="pointer"
                @click="customerPickupShow"
                >新增提货地址</span
              >
            </div>
            <div class="minheight" :class="{ maxheight: customerPickup }">
              <el-form
                ref="customerPickupAddress"
                :model="customerPickupAddress"
                size="mini"
                :rules="rules"
              >
                <el-form-item label-width="150px" prop="stateList">
                  <div slot="label">所在地区：</div>
                  <div class="block">
                    <el-cascader
                      v-model="stateList"
                      :options="stateIds"
                      @change="handleChange"
                    />
                  </div>
                </el-form-item>
                <el-form-item label="" label-width="150px" prop="address">
                  <el-input
                    v-model="customerPickupAddress.address"
                    placeholder="详细地址"
                    autocomplete="off"
                    style="width: 100%"
                    size="mini"
                  />
                </el-form-item>
                <el-form-item label-width="150px" prop="linkMan">
                  <div slot="label">联系人：</div>
                  <el-input
                    v-model="customerPickupAddress.linkMan"
                    autocomplete="off"
                    style="width: 100%"
                    size="mini"
                  />
                </el-form-item>
                <el-form-item label-width="150px" prop="contactWay">
                  <div slot="label">手机号码：</div>
                  <el-input
                    v-model="customerPickupAddress.contactWay"
                    autocomplete="off"
                    style="width: 100%"
                    size="mini"
                  />
                </el-form-item>

                <div class="text-center margin-bottom">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="saveCustomerPickupAddress"
                    >保存提货人信息</el-button
                  >
                  <el-button
                    size="mini"
                    type="primary"
                    @click="customerPickupHide"
                    >取消编辑</el-button
                  >
                </div>
              </el-form>
            </div>
            <el-form-item
              v-if="waybillInfo.selfDelivered"
              prop="pickUpGoodsAddres"
            >
              <div slot="label">装柜地址：</div>
              <div class="padding-lr">
                <template v-for="(item, index) in addressesData">
                  <!-- v-if="
                            showMoreAddress ||
                              (!showMoreAddress && item.defaultValue)
                          " -->
                  <div
                    v-if="
                      showMoreAddress || (!showMoreAddress && item.defaultValue)
                    "
                    :key="index"
                    class="address-item padding-lr margin-bottom-sm text-sm"
                    :class="{ 'address-active': item.defaultValue }"
                    @click="selectAddress(index)"
                  >
                    <el-row>
                      <el-col :span="3">
                        {{ item.linkMan }}
                      </el-col>
                      <el-col :span="14">
                        {{ item.address }}
                      </el-col>
                      <el-col :span="7">
                        {{ item.contactWay }}
                      </el-col>
                    </el-row>
                  </div>
                </template>
              </div>
              <div
                v-if="showAddress"
                class="text-sm"
                @click="showMoreAddress = !showMoreAddress"
              >
                <span v-if="showMoreAddress">
                  收起地址
                  <i class="el-icon-arrow-up" />
                </span>
                <span v-else>
                  更多地址
                  <i class="el-icon-arrow-down" />
                </span>
              </div>
            </el-form-item>
            <div class="text-gray margin-bottom-sm">
              如装柜不在装柜时间段内，需提前联系对应销售，通知九方做收货准备
            </div>
            <el-form-item prop="etInStock" v-if="buyFclLclFalg">
              <div slot="label">装柜时间：</div>
              <el-row>
                <el-col :span="12">
                  <el-date-picker
                    v-model="waybillInfo.etInStockDay"
                    type="date"
                    placeholder="选择日期"
                    :picker-options="pickerOptions"
                    value-format="yyyy-MM-dd"
                    style="width: 100%"
                    :editable="false"
                    @change="changeEtInStock"
                  />
                </el-col>
                <el-col :span="12">
                  <!-- <el-form-item prop="etInStockTime"> -->
                  <el-select
                    v-model="waybillInfo.etInStockTime"
                    placeholder="请选择时间段"
                    @change="changeEtInStock"
                  >
                    <el-option
                      v-for="item in timeOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                  <!-- </el-form-item> -->
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item label="备注：">
              <el-input
                v-model="waybillInfo.customerRemark"
                type="textarea"
                :rows="4"
                clearable
              />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="padding-40">
          <el-form
            ref="waybillInfo"
            :model="waybillInfo"
            size="mini"
            label-width="130px"
            label-position="left"
            :rules="rules"
          >
            <el-form-item prop="referenceNo">
              <div slot="label">
                参考号：
                <el-tooltip class="item" effect="light" placement="right">
                  <div slot="content">方便您自己用来识别此运单的任意号码。</div>
                  <i class="el-icon-question icon-absolute text-yellow" />
                </el-tooltip>
              </div>

              <el-input
                v-model="waybillInfo.referenceNo"
                maxlength="50"
                clearable
                placeholder="请填写英文，数字或者 -，不能超过50位"
              />
            </el-form-item>
            <div class="flex justify-end">
              <el-button
                type="text"
                class="text-sm"
                @click="selectSenderCompany"
              >
                {{ SenderCompanyType ? '新建发件人公司' : '选择发件人公司' }}
              </el-button>
            </div>

            <div v-show="SenderCompanyType">
              <el-form-item prop="custoemrSenderId">
                <div slot="label">发件人公司名(中)：</div>
                <el-tooltip
                  class="item"
                  content="点击输入可快速搜索"
                  effect="light"
                  placement="top-end"
                >
                  <el-select
                    v-model="waybillInfo.custoemrSenderId"
                    filterable
                    placeholder="请选择"
                    @change="changeSender"
                  >
                    <el-option
                      v-for="item in customerShipperMap"
                      :key="item.id"
                      :label="item.shipperCompanyCN"
                      :value="parseInt(item.id)"
                    />
                  </el-select>
                </el-tooltip>
              </el-form-item>
              <el-form-item prop="shipperCompany">
                <div slot="label">发件人公司名(英)：</div>
                <el-input v-model="waybillInfo.senderCompany" disabled />
              </el-form-item>
              <el-form-item prop="shipperAttn">
                <div slot="label">联系人：</div>
                <el-input v-model="waybillInfo.senderLinkMan" disabled />
              </el-form-item>

              <el-form-item prop="shipperPhone">
                <div slot="label">电话：</div>
                <el-input v-model="waybillInfo.senderPhone" disabled />
              </el-form-item>

              <el-form-item prop="shipperAddress">
                <div slot="label">地址：</div>
                <el-input v-model="waybillInfo.senderAdress" disabled />
              </el-form-item>
            </div>

            <div v-show="!SenderCompanyType">
              <el-form-item prop="senderCompany">
                <div slot="label">发件人公司名(英)：</div>
                <el-input
                  v-model="waybillInfo.senderCompany"
                  maxlength="100"
                  clearable
                  placeholder="请填写发件人公司名(英)"
                />
              </el-form-item>
              <el-form-item prop="senderCompanyCN">
                <div slot="label">发件人公司名(中)：</div>
                <el-input
                  v-model="waybillInfo.senderCompanyCN"
                  maxlength="100"
                  clearable
                  placeholder="请填写发件人公司名(中)"
                />
              </el-form-item>
              <el-form-item prop="senderLinkMan">
                <div slot="label">联系人：</div>
                <el-input
                  v-model="waybillInfo.senderLinkMan"
                  clearable
                  maxlength="20"
                  placeholder="请填写联系人"
                />
              </el-form-item>

              <el-form-item prop="senderPhone">
                <div slot="label">电话：</div>
                <el-input
                  v-model="waybillInfo.senderPhone"
                  clearable
                  maxlength="20"
                  placeholder="请填写电话"
                />
              </el-form-item>

              <el-form-item prop="senderZipCode">
                <div slot="label">邮编：</div>
                <el-input
                  v-model="waybillInfo.senderZipCode"
                  clearable
                  maxlength="20"
                  placeholder="请填写邮编"
                />
              </el-form-item>
              <el-form-item prop="senderEnterpriseCreditCode">
                <div slot="label">企业信用代码：</div>
                <el-input
                  v-model="waybillInfo.senderEnterpriseCreditCode"
                  maxlength="20"
                  clearable
                  placeholder="请填写企业信用代码"
                />
              </el-form-item>
              <el-form-item prop="senderAdress">
                <div slot="label">详细地址(英)</div>
                <el-input
                  v-model="waybillInfo.senderAdress"
                  maxlength="100"
                  clearable
                  placeholder="请填写详细地址(英)"
                />
              </el-form-item>
            </div>

            <el-form-item label="通知人：">
              <el-input
                v-model="waybillInfo.masterNumberNotifier"
                type="textarea"
                clearable
              />
            </el-form-item>
            <el-form-item label="收件人：">
              <el-input
                v-model="waybillInfo.houseNumberReceiver"
                type="textarea"
                :rows="4"
                placeholder="公司英文名
  公司英文地址
  TEL：联系电话
  VAT ：等"
                clearable
              />
            </el-form-item>

            <div class="minheight" :class="{ maxheight: flag }">
              <el-form-item
                v-if="waybillInfo.isVatAndEori === 1"
                label="选择进口商："
                label-width="150px"
                prop="customerImporterId"
              >
                <el-select
                  v-model="waybillInfo.customerImporterId"
                  size="mini"
                  style="width: 60%"
                >
                  <el-option
                    v-for="(v, i) in customerImporterIds"
                    :key="i"
                    :label="v.importerCompany"
                    :value="parseInt(v.id)"
                  />
                </el-select>
                <el-link :underline="false" type="primary" @click="serviceShow"
                  >新增进口商</el-link
                >
              </el-form-item>
            </div>
            <div class="minheight" :class="{ maxheight: importerShow }">
              <el-form-item label-width="150px" prop="importerCompanyName">
                <div slot="label">进口商公司名：</div>
                <el-input
                  v-model="waybillInfo.importerCompanyName"
                  autocomplete="off"
                  style="width: 50%"
                  size="mini"
                />
                <el-link :underline="false" type="primary" @click="importerHide"
                  >返回</el-link
                >
              </el-form-item>
              <el-form-item
                label="进口商联系人："
                label-width="150px"
                prop="importerLinkMan"
              >
                <el-input
                  v-model="waybillInfo.importerLinkMan"
                  autocomplete="off"
                  style="width: 75%"
                  size="mini"
                />
              </el-form-item>
              <el-form-item
                label="进口商电话："
                label-width="150px"
                prop="importerPhone"
              >
                <el-input
                  v-model="waybillInfo.importerPhone"
                  autocomplete="off"
                  style="width: 75%"
                  size="mini"
                />
              </el-form-item>
              <el-form-item label-width="150px" prop="importerZipCode">
                <div slot="label">进口商邮编：</div>
                <el-input
                  v-model="waybillInfo.importerZipCode"
                  autocomplete="off"
                  style="width: 75%"
                  size="mini"
                />
              </el-form-item>
              <el-form-item label-width="150px" prop="vat">
                <div slot="label">进口商VAT：</div>
                <el-input
                  v-model="waybillInfo.vat"
                  autocomplete="off"
                  style="width: 75%"
                  size="mini"
                />
              </el-form-item>
              <el-form-item label-width="150px" prop="eori">
                <div slot="label">进口商EORI：</div>
                <el-input
                  v-model="waybillInfo.eori"
                  autocomplete="off"
                  style="width: 75%"
                  size="mini"
                />
              </el-form-item>
              <el-form-item label-width="150px" prop="importerAddress">
                <div slot="label">进口商地址：</div>
                <el-input
                  v-model="waybillInfo.importerAddress"
                  autocomplete="off"
                  style="width: 75%"
                  size="mini"
                />
              </el-form-item>
            </div>
          </el-form>
        </el-col>
      </el-row>
    </el-card>

    <div class="text-center margin-tb">
      <el-button size="medium" type="primary" @click="waybillInfoSave(10)"
        >提交待确认</el-button
      >
      <el-button size="medium" type="primary" @click="waybillInfoSave(20)"
        >完成并提交</el-button
      >
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { uncompileStr } from '@/utils'
import { getPcas } from '@/utils/city-pcas.js'
import { getInfo } from '@/api/user'
import { customerpickupadderssList, customerShipperList } from '@/api/myProfile'
import {
  initPageData,
  saveCustomerPickupAddress,
  saveG2GAirWaybill,
  getWaybillById,
  queryCustomerImporter,
  uploadWaybillFile,
} from '@/api/waybill'
import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')
export default {
  components: {},

  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return (
            time.getTime() < Date.now() - 3600 * 1000 * 24 ||
            time.getDay() === 0
          )
        },
      },
      showNb: false,
      buyFclLclFalg: false,
      buyInsuranceFlag: true,
      showMoreAddress: false,
      showAddress: false,
      SenderCompanyType: true,
      timeOptions: [
        '09:00-11:00',
        '11:00-13:00',
        '13:00-15:00',
        '15:00-17:00',
        '17:00-19:00',
        '19:00-21:00',
      ],
      boxMap: [{ cabinetNumber: '', cabinetType: '' }],
      rules: {
        countryId: [
          { required: true, message: '请选择国家', trigger: 'change' },
        ],
        shipmentPort: [
          { required: true, message: '请选择起运港', trigger: 'change' },
        ],
        destinationPort: [
          { required: true, message: '请选择目的港', trigger: 'change' },
        ],
        senderPhone: [
          { required: true, message: '请填写电话', trigger: 'blur' },
        ],
        senderLinkMan: [
          { required: true, message: '请填写联系人', trigger: 'blur' },
        ],
        senderCompany: [
          {
            required: true,
            message: '请填写发件人公司名(英)',
            trigger: 'blur',
          },
        ],
        senderCompanyCN: [
          {
            required: true,
            message: '请填写发件人公司名(中)',
            trigger: 'blur',
          },
        ],
        shippingWay: [
          { required: true, message: '请选择物流方式', trigger: 'change' },
        ],
        customerActualWeight: [
          {
            required: true,
            message: '请输入正实数',
            trigger: 'blur',
          },
          {
            pattern:
              /(^[0-9]([0-9]+)?(\.[0-9]{1,3})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '须为数字,可留3位小数',
          },
        ],
        // cabinetNumber: [
        //   { required: true, message: '请填写正整数', trigger: 'blur' },
        //   { type: 'number', message: '必须为数字值' }
        // ],
        // cabinetType: [
        //   { required: true, message: '请选择柜型', trigger: 'change' }
        // ],
        selfDelivered: [
          { required: true, message: '请选择装柜方式', trigger: 'change' },
        ],
        customerVolume: [
          {
            required: true,
            message: '请输入正实数',
            trigger: 'blur',
          },
          {
            pattern:
              /(^[0-9]([0-9]+)?(\.[0-9]{1,3})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '须为数字,可留3位小数',
          },
        ],
        customerTotalPackages: [
          { required: true, message: '请输入正整数', trigger: 'blur' },
          {
            pattern: /^[1-9]\d*$/,
            message: '件数须为正整数',
          },
        ],
        isCustomerDeclaration: [
          { required: true, message: '请选择是否报关', trigger: 'change' },
        ],
        etInStock: [
          { required: true, message: '请选择日期', trigger: 'change' },
        ],
        custoemrSenderId: [
          { required: true, message: '请选择发件人公司', trigger: 'change' },
        ],

        senderAdress: [
          {
            required: true,
            message: '请填写地址',
            trigger: 'blur',
          },
        ],
        customerImporterId: [
          { required: true, message: '请选择进口商', trigger: 'change' },
        ],
        importerCompanyName: [
          { required: true, message: '请填写进口商公司名', trigger: 'blur' },
        ],
        importerZipCode: [
          { required: true, message: '请填写进口商邮编', trigger: 'blur' },
        ],
        vat: [{ required: true, message: '请填写进口商VAT', trigger: 'blur' }],
        eori: [
          { required: true, message: '请填写进口商EORI', trigger: 'blur' },
        ],

        importerAddress: [
          { required: true, message: '请填写进口商地址', trigger: 'blur' },
        ],
        // 提货人信息
        // stateList: [
        //   { required: true, message: '请选择所在地区', trigger: 'change' }
        // ],
        linkMan: [{ required: true, message: '请填写联系人', trigger: 'blur' }],
        contactWay: [
          { required: true, message: '请填写手机号码', trigger: 'blur' },
        ],
        // 提货信息
        // pickUpGoodsAntipateTime: [
        //   { required: true, message: '请选择预计提货时间', trigger: 'blur' }
        // ],
        pickUpGoodsAddres: [
          { required: true, message: '请填写提货地址', trigger: 'blur' },
        ],
        senderEnterpriseCreditCode: [
          { required: true, message: '请填写企业信用代码', trigger: 'blur' },
        ],
      },
      flag: false, // 隐藏
      flags: false, // 显示
      importerShow: true, // 进口商
      pickUpGoods: false, // 是是否需要提货
      estimatedDeli: true, // 预计送货时间
      customerPickup: true, // 新增收获地址
      customerShipperMap: [],
      customerIds: [], // 客户
      countryIds: [], // 国家
      airlineIds: [], // 航空公司
      shipownerIds: [], // 船公司
      configPortMap: [], // 港口信息
      airlineMap: [], // 机场信息
      shippingWayIds: [], // 物流方法
      customerImporterIds: [], // 选择进口商
      stateIds: [], // 省份
      cityIds: [], // 城市
      areaIds: [], // 区县
      loading: false, // 客户远程搜索
      waybillInfo: {
        // customerId: '',
        countryId: '',
        shipmentPort: '', // 起运港
        destinationPort: '', // 目的港
        shipOrAirlineCompany: '', // 船公司/航空公司
        shippingWay: 'AIR', // 物流方式
        customerActualWeight: '',
        customerVolume: '',
        customerTotalPackages: '',
        isCustomerDeclaration: 0, // 是否报关
        selfDelivered: '', // 装柜方式
        isBuyInsurance: 0,
        examineDeclareNameCn: '', // 品名
        isVatAndEori: 0, // 自有VAT和EORI：0.否 1.是
        customerImporterId: '', // 进口商ID
        importerCompanyName: '', // 进口商公司名
        importerLinkMan: '', // 进口商联系人
        importerPhone: '', // 进口商电话
        importerZipCode: '', // 进口商邮编
        vat: '', // 进口商VAT
        eori: '', // 进口商EORI
        importerAddress: '', // 进口商地址
        pickUpGoodsAddres: '', // 提货地址
        pickUpGoodsAntipateTime: '', // 提货预约时间

        status: 20, // 提交为交寄
        extraAttributes: [], // 上传文件路径
        masterNumberNotifier: 'SAME AS CONSIGNEE', // 通知人
        referenceNo: '',
        customerRemark: '',
        senderCompany: '',
        senderCompanyCN: '',
        senderLinkMan: '',
        senderPhone: '',
        senderAdress: '',
        senderZipCode: '',
        senderEnterpriseCreditCode: '',
        houseNumberReceiver: '',
        nameDescription: '',
        custoemrSenderId: '',
        etInStockDay: '',
        etInStockTime: '',
        // shipperAttn: '',
        // shipperPhone: '',
        // shipperAddress: ''
      },
      stateList: [], // 存储地区信息
      customerPickupAddress: {
        id: '',
        // 客户提货地址
        state: '', // 省
        city: '', // 城市
        area: '', // 区
        street: '', // 街道
        address: '', // 详细地址
        linkMan: '', // 联系人
        contactWay: '', // 联系方式
        defaultValue: 0, // 默认值
        cuser: '', // 客户id
      },
      customerInfo: {
        customerName: '', // 客户名称
        countryName: '', // 国家名
        shipmentPortCode: '', // 启运港编码
        destinationPortCode: '', // 目的港编码
        countryName: '', // 国家名
        airlineCode: '', // 航空公司
      },
      isNotOptions: {
        1: '是',
        0: '否',
      },
      currencySource: {}, // 币种
      costNameSource: {}, // 费用名称
      customerMap: {}, // 客户
      receivableData: [], // 应收表格数据
      addressesData: [], // 提货地址数据
    }
  },
  watch: {
    // 如果路由有变化，会再次执行该方法
    $route: 'fetchData',
    'waybillInfo.isBuyInsurance': {
      handler(val, oldVal) {
        console.log('provinceId :>> ', val)
        console.log('provinceId oldVal :>> ', oldVal)
        if (val && val == 1) {
          this.buyInsuranceFlag = false
        } else {
          this.buyInsuranceFlag = true
        }
      },
      deep: true,
      immediate: true,
    },
    'waybillInfo.shippingWay': {
      handler(val, oldVal) {
        console.log('provinceId :>> ', val)
        console.log('provinceId oldVal :>> ', oldVal)
        if (val && val == 'AIR') {
          this.buyFclLclFalg = false
        } else {
          this.buyFclLclFalg = true
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(['publicData']),
  },
  created() {
    //判断是否是 宁波系统
    let url = window.location.href
    let arr = url.split('#')
    console.log('arr: ', arr[0]);
    if (arr[0] === 'http://47.96.65.20:18887/') {
      this.showNb = true
    }
  },
  mounted() {
    this.initPageData()
    this.initPickupaddress()
    this.queryCustomerImporter()
    this.customerShipperList()
  },
  methods: {
    // 获取提货地址
    async initPickupaddress() {
      const res = await customerpickupadderssList({
        authorization: getToken(),
      })
      this.addressesData = res
      this.showAddress = true
    },
    async customerShipperList() {
      this.customerShipperMap = await customerShipperList({
        authorization: getToken(),
      })
    },
    // 获取进口商信息
    async queryCustomerImporter() {
      const res = await queryCustomerImporter({
        authorization: getToken(),
      })
      if (res.data && res.data != null && res.data.length > 0) {
        this.customerImporterIds = res.data
      }
    },
    changeSender(val) {
      for (const i of this.customerShipperMap) {
        if (
          this.waybillInfo.custoemrSenderId &&
          this.waybillInfo.custoemrSenderId === i.id
        ) {
          this.waybillInfo.senderLinkMan = i.shipperAttn
          this.waybillInfo.senderPhone = i.shipperPhone
          this.waybillInfo.senderAdress = i.shipperAddress
          this.waybillInfo.senderCompany = i.shipperCompany
        }
      }
    },
    beforeUpload(file) {
      const isLt50M = file.size / 1024 / 1024 < 50

      if (!isLt50M) {
        this.$message.error('上传文件大小不能超过 50MB!')
        return false
      }
      return true
    },
    async uploadFn(params) {
      console.log('params', params)
      if (!this.beforeUpload(params.file)) return
      const formData = new FormData()
      // 通过 FormData 对象上传文件
      formData.append(this.fileName, params.file)

      const data = await uploadWaybillFile(formData)
      console.log('data :>> ', data)
      if (data.code === 200) {
        const arr = [...this.waybillInfo.extraAttributes, data.fileUrl]
        this.waybillInfo.extraAttributes = arr
      } else {
        this.$message.error('上传失败!')
      }
    },
    removeFile(index) {
      this.waybillInfo.extraAttributes.splice(index, 1)
    },
    // 切换选择/新建
    selectSenderCompany() {
      if (this.SenderCompanyType) {
        this.SenderCompanyType = !this.SenderCompanyType
        this.waybillInfo.senderCompany = ''
        this.waybillInfo.custoemrSenderId = ''
        this.waybillInfo.senderLinkMan = ''
        this.waybillInfo.senderPhone = ''
        this.waybillInfo.senderAdress = ''
      } else {
        this.$confirm('已填发件人公司资料将被清空？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.SenderCompanyType = !this.SenderCompanyType
            this.waybillInfo.senderCompany = ''
            this.waybillInfo.senderCompanyCN = ''
            this.waybillInfo.senderLinkMan = ''
            this.waybillInfo.senderPhone = ''
            this.waybillInfo.senderZipCode = ''
            this.waybillInfo.senderEnterpriseCreditCode = ''
            this.waybillInfo.senderAdress = ''
          })
          .catch(() => {})
      }
    },
    selectAddress(index) {
      for (const i of this.addressesData) {
        i.defaultValue = 0
      }
      this.addressesData[index].defaultValue = 1
      this.showMoreAddress = false
    },
    changeCustomerDeclaration(val) {
      this.$delete(this.waybillInfo, 'isCustomerDeclaration')
      this.$set(this.waybillInfo, 'isCustomerDeclaration', val)
    },
    changeData(scope) {
      if (scope.row.count && scope.row.unitPrice) {
        this.$set(
          scope.row,
          'totalCost',
          (scope.row.count * scope.row.unitPrice * 1000) / 1000
        )
        this.$set(
          scope.row,
          'remain',
          (scope.row.count * scope.row.unitPrice * 1000) / 1000
        )
      }
    },
    editReceiveBySale(scope) {
      const data = {}
      // console.log(scope.row.customerId);
      data['serCusId'] = scope.row.serCusId // 公司
      data['accountDate'] = scope.row.accountDate
      this.receivableData.push(data)
    },
    delData(scope) {
      const index = scope.$index
      this.receivableData.splice(index, 1)
    },
    onAdd(val) {
      if (val.cabinetNumber && val.cabinetType) {
        this.boxMap.push({ cabinetNumber: '', cabinetType: '' })
      } else {
        this.$message.error('请先填写当前柜型柜量再新增')
      }
    },
    removeDomain(val) {
      const index = this.boxMap.indexOf(val)
      if (index !== -1 && this.boxMap.length > 1) {
        this.boxMap.splice(index, 1)
      }
    },
    serviceShow() {
      // 展示进口商信息
      this.flag = true
      this.importerShow = false
    },
    importerHide() {
      // 隐藏进口商信息
      this.flag = false
      this.importerShow = true
    },
    pickUpGoodsShow() {
      this.pickUpGoods = true
      this.estimatedDeli = false
    },
    estimatedDeliShow() {
      this.pickUpGoods = false
      this.estimatedDeli = true
    },
    customerPickupShow() {
      this.customerPickup = false
    },
    customerPickupHide() {
      // 隐藏进口商信息
      this.customerPickup = true
    },
    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    handleChange(val) {
      if (!val) return
      this.customerPickupAddress.state = val[0]
      this.customerPickupAddress.city = val[1]
      this.customerPickupAddress.area = val[2]
      this.customerPickupAddress.street = val[3]
    },
    changeEtInStock() {
      const cf = this.waybillInfo
      if (cf.etInStockDay && cf.etInStockTime) {
        this.$delete(cf, 'etInStock')
        this.$set(cf, 'etInStock', cf.etInStockDay + ' ' + cf.etInStockTime)
      } else if (cf.etInStockDay) {
        this.$delete(cf, 'etInStock')
        this.$set(cf, 'etInStock', cf.etInStockDay + ' ' + cf.etInStockTime)
      } else {
        this.$delete(cf, 'etInStock')
        this.$set(cf, 'etInStock', '')
      }
    },
    async initPageData() {
      this.stateIds = getPcas() // 省份
      this.airlineMap = this.publicData.airPortMap // 机场管理 - 机场代码

      this.configPortMap = this.publicData.portMap // 港口信息
      const res = await initPageData({})
      // console.log(res)
      this.customerMap = res.customerMap // 客户-数据太多太卡了，直接远程搜索
      this.countryIds = res.countryMap // 国家
      // this.airlineMap = res.airlineMap //机场管理 - 机场代码

      // this.configPortMap = res.configPortMap //港口信息
      // this.customerImporterIds = res.customerImporterMap; //选择进口商信息
      // this.shippingWayIds = res.channelTypes; //物流方法
      this.currencySource = res.currencySource // 币种
      this.costNameSource = res.costNameSource // 费用名称
      this.getWaybillById()
    },
    async getWaybillById() {
      if (this.$route.query.id) {
        const id = uncompileStr(this.$route.query.id)
        this.$store.dispatch('app/toggleDialog', true)
        const res = await getWaybillById({ id: id })
        // console.log('res: ', res)
        const waybill = res.data.waybill
        this.waybillInfo = waybill
        if (waybill.shippingWay === 'FCLG') {
          this.$set(this.waybillInfo, 'shippingWay', 'FCL')
        } else if (waybill.shippingWay === 'LCLG') {
          this.$set(this.waybillInfo, 'shippingWay', 'LCL')
        }

        // 柜量-柜型
        const arr = waybill.cabinetInfo
          ? waybill.cabinetInfo.split(';')
          : ['', '']
        let cabinetInfo = []
        this.boxMap = []
        if (arr.length > 0) {
          for (const k of arr) {
            cabinetInfo = k.split('*')
            this.boxMap.push({
              cabinetNumber: parseInt(cabinetInfo[0]), // 柜量
              cabinetType: cabinetInfo[1], // 柜型
            })
          }
        }

        // 装柜时间
        if (waybill.etInStock) {
          const etInStock = waybill.etInStock.split(' ')

          this.waybillInfo.etInStockDay = etInStock[0]
          this.waybillInfo.etInStockTime = etInStock[1]
        }
        for (const i of this.addressesData) {
          if (
            i.linkMan === this.waybillInfo.pickUpGoodsLinkMan &&
            i.contactWay === this.waybillInfo.pickUpGoodsPhone &&
            i.address === this.waybillInfo.pickUpGoodsAddres
          ) {
            i.defaultValue = 1
          }
        }
        this.$store.dispatch('app/toggleDialog', false)
      }
    },

    async saveCustomerPickupAddress() {
      // 新增客户收货地址
      const res = await saveCustomerPickupAddress(this.customerPickupAddress)
      console.log(res)
      if (res.code !== 200) {
        this.$message.error(res.message)
      } else {
        this.$message.success('新增地址成功')
        this.columns = res.data
        this.initPickupaddress()
        console.log('this.columns', this.columns)
      }
    },
    async waybillInfoSave(status) {
      // 保存运单信息
      if (!this.waybillInfo.countryId) {
        this.$message.error('请选择国家')
        return
      } else if (!this.waybillInfo.shipmentPort) {
        this.$message.error('请选择起运港')
        return
      } else if (!this.waybillInfo.destinationPort) {
        this.$message.error('请选择目的港')
        return
      } else if (
        (this.waybillInfo.isCustomerDeclaration === null ||
          this.waybillInfo.isCustomerDeclaration === '') &&
        this.waybillInfo.shippingWay !== 'AIR'
      ) {
        this.$message.error('请选择装柜方式')
        return
      } else if (
        !this.waybillInfo.etInStockDay &&
        this.waybillInfo.shippingWay !== 'AIR'
      ) {
        this.$message.error('请选择装柜时间时间')
        return
      } else if (!this.waybillInfo.custoemrSenderId && this.SenderCompanyType) {
        this.$message.error('请选择发件人公司名(中)')
        return
      } else if (
        this.waybillInfo.customerActualWeight !== '' &&
        this.waybillInfo.customerActualWeight == 0
      ) {
        this.$message.error('请填写实重')
        return
      } else if (
        !this.waybillInfo.customerVolume &&
        (this.waybillInfo.shippingWay === 'FCL' ||
          this.waybillInfo.shippingWay === 'LCL')
      ) {
        this.$message.error('请填写体积')
        return
      } else if (!this.waybillInfo.customerTotalPackages) {
        this.$message.error('请填写件数')
        return
      } else if (
        this.waybillInfo.isCustomerDeclaration === null ||
        this.waybillInfo.isCustomerDeclaration === ''
      ) {
        this.$message.error('请选择是否报关')
        return
      }
      // 校验体积
      const reg =
        /(^[1-9]([0-9]+)?(\.[0-9]{1,3})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
      if (
        this.waybillInfo.customerVolume &&
        (this.waybillInfo.shippingWay === 'FCL' ||
          this.waybillInfo.shippingWay === 'LCL') &&
        !reg.test(this.waybillInfo.customerVolume)
      ) {
        this.$message.error('体积只能为正实数')
        return
      }
      // 校验件数
      const rege = /^[1-9]\d*$/
      if (!rege.test(this.waybillInfo.customerTotalPackages)) {
        this.$message.error('件数只能为正整数')
        return
      }
      if (this.addressesData.length > 0) {
        for (const i of this.addressesData) {
          if (i.defaultValue === 1) {
            this.waybillInfo['pickUpGoodsAddres'] = i.address
            this.waybillInfo['pickUpGoodsLinkMan'] = i.linkMan
            this.waybillInfo['pickUpGoodsPhone'] = i.contactWay
          }
        }
      }
      if (this.SenderCompanyType) {
        for (const i of this.customerShipperMap) {
          if (i.id === this.waybillInfo.custoemrSenderId) {
            this.waybillInfo['senderCompanyCN'] = i.shipperCompanyCN
          }
        }
      }

      if (
        this.waybillInfo.shippingWay &&
        (this.waybillInfo.shippingWay === 'FCL' ||
          this.waybillInfo.shippingWay === 'LCL')
      ) {
        if (!this.waybillInfo.isBuyInsurance) {
          this.$message.warning('默认不购买保险！')
        }
        if (
          this.waybillInfo.isBuyInsurance &&
          this.waybillInfo.isBuyInsurance == 1
        ) {
          if (!this.waybillInfo.totalPurchasingPrice) {
            this.$message.error('购买保险请填写采购总价！')
            return
          }
          if (!this.waybillInfo.nameDescription) {
            this.$message.error('购买保险请填写品名！')
            return
          }
        }
      }
      // 拼接-柜量*柜型
      let strInfo = ''
      const arr = []
      if (this.waybillInfo.shippingWay === 'FCL') {
        for (const i of this.boxMap) {
          if (i.cabinetNumber && i.cabinetType) {
            strInfo = i.cabinetNumber + '*' + i.cabinetType
            arr.push(strInfo)
          } else {
            return this.$message.error('请填写柜量柜型！')
          }
          const arrJoinString = arr.join(';')
          console.log('arrJoinString: ', arrJoinString)
          this.waybillInfo['cabinetInfo'] = arrJoinString
        }
      }

      this.waybillInfo['status'] = status
      this.$store.dispatch('app/toggleDialog', true)
      const res = await saveG2GAirWaybill(this.waybillInfo)
      if (res.code === 200) {
        this.$message.success('提交成功')
        setTimeout(function () {
          window.open('#/waybillManagement/waybillList', '_self')
        }, 1000)
      } else {
        this.$message.error('提交失败')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
  },
}
</script>

<style scoped lang="scss">
.el-card {
  margin-top: 10px;
  margin-bottom: 20px;
  margin-left: 10px;
  margin-right: 10px;
}

.maxheight {
  display: none;
}
.address-item {
  border: 1px solid #ccc;
}

.address-active {
  position: relative;
  border: 1px solid #9dc9f6;
}
.address-active::after {
  content: '';
  background: url('../../assets/images/choose.png');
  position: absolute;
  background-size: 18px 19px;
  top: 50%;
  right: 2%;
  transform: translate(-50%, -50%);
  width: 18px;
  height: 19px;
}
</style>
<style scoped>
/deep/ .el-upload--text {
  width: 0%;
}
</style>
